package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.mvp.mode.ResourceAdministrationModel;
import com.eostoken.eos_wallet.mvp.presenter.ResourceAdministrationPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.ResourceAdministrationView;
import com.eostoken.eos_wallet.ui.fragmentfactory.FragmentFactory;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.ConversionUnits;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.eostoken.eos_wallet.view.BatteryView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.ui.activity.ResourceAdministrationActivity.bdToEOS;
import static com.eostoken.eos_wallet.ui.activity.ResourceAdministrationActivity.percent;
import static com.eostoken.eos_wallet.utils.Constants.ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.BUY_SELL_RAM;
import static com.eostoken.eos_wallet.utils.Constants.CONFIRM_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TRANSACTION;
import static com.eostoken.eos_wallet.utils.Constants.MORTGAGE_REDEEM;


public class ResourceAdministrationFragment extends BaseFragment<ResourceAdministrationModel, ResourceAdministrationView, ResourceAdministrationPresenterImpl> implements ResourceAdministrationView {
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.totalAssetsTv)
    AppCompatTextView totalAssetsTv;
    @BindView(R.id.balanceTv)
    AppCompatTextView balanceTv;
    @BindView(R.id.redemptionTv)
    AppCompatTextView redemptionTv;
    @BindView(R.id.pledgeTv)
    AppCompatTextView pledgeTv;
    @BindView(R.id.layout1)
    LinearLayout layout1;
    @BindView(R.id.RAMView)
    BatteryView RAMView;
    @BindView(R.id.availableRAMTv)
    AppCompatTextView availableRAMTv;
    @BindView(R.id.buyBtn)
    QMUIRoundButton buyBtn;
    @BindView(R.id.saleBtn)
    QMUIRoundButton saleBtn;
    @BindView(R.id.layout2)
    LinearLayout layout2;
    @BindView(R.id.CPUView)
    BatteryView CPUView;
    @BindView(R.id.availableCPUTv)
    AppCompatTextView availableCPUTv;
    @BindView(R.id.broadbandiew)
    BatteryView broadbandiew;
    @BindView(R.id.availableBroadbandTv)
    AppCompatTextView availableBroadbandTv;
    @BindView(R.id.pledgeBtn)
    QMUIRoundButton pledgeBtn;
    @BindView(R.id.ransomBtn)
    QMUIRoundButton ransomBtn;
    @BindView(R.id.layout3)
    LinearLayout layout3;

    private boolean isBuy = true;
    private boolean isPledge = true;
    private String accountInfoJSON;
    private String accountName;
    private String pledge;//
    private BigDecimal bgNetWeight;//抵押网络
    private BigDecimal bgCpuWeight;//抵押CPU
    private BigDecimal bgPledge;//抵押总额
    private BigDecimal bdBalance;//EOS余额
    private BigDecimal bdRamQuota;//内存总量
    private BigDecimal bdRamUsage;//已用内存
    private BigDecimal bdRamResidue;//剩余内存
    private BigDecimal bdCPUMax;//CPU最大值
    private BigDecimal bdCPUUsed;//CPU已使用
    private BigDecimal bdCPUAvailable;//CPU可用
    private BigDecimal bdNetMax;//CPU最大值
    private BigDecimal bdNetUsed;//CPU已使用
    private BigDecimal bdNetAvailable;//CPU可用
    private BigDecimal bdRedemption;//赎回中

    private String balance = "0";
    private String redemption = "0";
    private AccountInfo accountInfo;

//    private static class LazyHolder {
//        private static final ResourceAdministrationFragment INSTANCE = new ResourceAdministrationFragment();
//    }
//
//    public static final ResourceAdministrationFragment getInstance(String accountInfo) {
//        Bundle bundle = new Bundle();
//        bundle.putString(EXTRA_ACCOUNT_INFO, accountInfo);
//        ResourceAdministrationFragment.LazyHolder.INSTANCE.setArguments(bundle);
//        return ResourceAdministrationFragment.LazyHolder.INSTANCE;
//    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_resource_administration;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        accountInfoJSON = bundle.getString(EXTRA_ACCOUNT_INFO, "");
        if (!ObjectUtils.isEmpty(accountInfoJSON)) {
            accountInfo = GsonUtils.fromJson(accountInfoJSON, AccountInfo.class);
        }
        accountName = WalletUtils.getCurrentAccountName();
        presenter.requestAccount(Params.getAccountPamars(accountName));
    }

    @Override
    protected void initView(View contentView) {
        topbar.setTitle(StringUtils.getString(R.string.str_resource_administration));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        initView();
    }

    private void initView() {
        if (!ObjectUtils.isEmpty(accountInfo)) {
            AccountInfo.RefundRequestBean refundRequestBean = accountInfo.getRefund_request();
            String aCPU = "0";
            String bNET = "0";
            if (refundRequestBean != null) {
                String redeemCPU = refundRequestBean.getCpu_amount();
                String redeemNET = refundRequestBean.getNet_amount();
                if (!ObjectUtils.isEmpty(redeemCPU)) {
                    String[] a = redeemCPU.split(" ");
                    aCPU = a[0];
                }
                if (!ObjectUtils.isEmpty(redeemNET)) {
                    String[] b = redeemNET.split(" ");
                    bNET = b[0];
                }
            }
            bdRedemption = new BigDecimal(aCPU).add(new BigDecimal(bNET));
            redemption = bdRedemption.setScale(4, BigDecimal.ROUND_HALF_DOWN).toPlainString();
            redemptionTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_blank), redemption));

            bgNetWeight = accountInfo.getNet_weight();
            bgCpuWeight = accountInfo.getCpu_weight();
            bgPledge = (bgNetWeight.add(bgCpuWeight)).divide(bdToEOS, 4, BigDecimal.ROUND_HALF_DOWN);
            pledge = bgPledge.toPlainString();
            pledgeTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_blank), pledge));//抵押
            balance = accountInfo.getCore_liquid_balance();
            if (ObjectUtils.isEmpty(balance)) {
                balance = "0.0000 MGP";
            }
            balanceTv.setText(balance);//余额

            String[] bArr = balance.split(" ");
            String b = bArr[0];
            bdBalance = new BigDecimal(b);
            String total = bgPledge.add(bdBalance).add(bdRedemption).setScale(4, BigDecimal.ROUND_HALF_DOWN).toPlainString();
            totalAssetsTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_blank), total));//总资产

            bdRamQuota = accountInfo.getRam_quota();
            String ramQuota = ConversionUnits.getRAMConversionUnit(bdRamQuota.longValue());
            bdRamUsage = accountInfo.getRam_usage();
            bdRamResidue = bdRamQuota.subtract(bdRamUsage);
            String ramAvailable = ConversionUnits.getRAMConversionUnit(bdRamResidue.longValue());
            availableRAMTv.setText(ramAvailable + "/" + ramQuota);

            BigDecimal bigDecimal = bdRamResidue.divide(bdRamQuota, 2, BigDecimal.ROUND_HALF_DOWN).multiply(percent);
            int RamPercent = bigDecimal.intValue();
            RAMView.setPower(RamPercent);

            AccountInfo.CpuLimitBean cpu_limit = accountInfo.getCpu_limit();
            bdCPUMax = cpu_limit.getMax();
//            bdCPUUsed = cpu_limit.getUsed();
            bdCPUAvailable = cpu_limit.getAvailable();


            int CPUPercent = bdCPUAvailable.divide(bdCPUMax, 2, BigDecimal.ROUND_HALF_DOWN).multiply(percent).intValue();
            CPUView.setPower(CPUPercent);
            String availableCPU = ConversionUnits.getCPUConversionUnit(bdCPUAvailable.longValue());
            String maxCPU = ConversionUnits.getCPUConversionUnit(bdCPUMax.longValue());
            availableCPUTv.setText(availableCPU + "/" + maxCPU);

            AccountInfo.NetLimitBean net_limit = accountInfo.getNet_limit();
            bdNetMax = net_limit.getMax();
            bdNetUsed = net_limit.getUsed();
            bdNetAvailable = net_limit.getAvailable();
            int NetPercent = bdNetAvailable.divide(bdNetMax, 2, BigDecimal.ROUND_HALF_DOWN).multiply(percent).intValue();
            broadbandiew.setPower(NetPercent);

            String netMax = ConversionUnits.getRAMConversionUnit(bdNetMax.longValue());
            String netAvailable = ConversionUnits.getRAMConversionUnit(bdNetAvailable.longValue());
            availableBroadbandTv.setText(netAvailable + "/" + netMax);
        }
    }

    @OnClick({R.id.buyBtn, R.id.saleBtn, R.id.pledgeBtn, R.id.ransomBtn})
    public void onViewClicked(View view) {
        Intent intent;
        Bundle bundle;
        Fragment fragment;
        switch (view.getId()) {
            case R.id.buyBtn:
                isBuy = true;
                fragment = FragmentFactory.getInstatic().getFragment(BUY_SELL_RAM);
                bundle = new Bundle();
                bundle.putBoolean(EXTRA_TRANSACTION, isBuy);
                bundle.putString(EXTRA_ACCOUNT_INFO, accountInfoJSON);
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "buyram", true);
                break;
            case R.id.saleBtn:
                isBuy = false;
                fragment = FragmentFactory.getInstatic().getFragment(BUY_SELL_RAM);
                bundle = new Bundle();
                bundle.putBoolean(EXTRA_TRANSACTION, isBuy);
                bundle.putString(EXTRA_ACCOUNT_INFO, accountInfoJSON);
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "sellram", true);
                break;
            case R.id.pledgeBtn:
                isPledge = true;
                fragment = FragmentFactory.getInstatic().getFragment(MORTGAGE_REDEEM);
                bundle = new Bundle();
                bundle.putString(EXTRA_ACCOUNT_INFO, accountInfoJSON);
                bundle.putBoolean(Constants.EXTRA_MORTGAGE, isPledge);
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "delegatebw", true);
                break;
            case R.id.ransomBtn:
                isPledge = false;
                fragment = FragmentFactory.getInstatic().getFragment(MORTGAGE_REDEEM);
                bundle = new Bundle();
                bundle.putString(EXTRA_ACCOUNT_INFO, accountInfoJSON);
                bundle.putBoolean(Constants.EXTRA_MORTGAGE, isPledge);
                fragment.setArguments(bundle);
                FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "undelegatebw", true);
                break;
        }
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        LogUtils.dTag("updateView==0", " updateView = " + responseSuccessCode);
        switch (responseSuccessCode) {
            case ACCOUNT_INFO:
                accountInfo = (AccountInfo) data;
                accountInfoJSON = GsonUtils.toJson(accountInfo);
                initView();
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        LogUtils.dTag("updateView==0", " onFailure = " + responseFailCode);
        switch (responseFailCode) {
            case ACCOUNT_INFO:

                break;
        }
    }

    @Override
    public ResourceAdministrationModel createModel() {
        return new ResourceAdministrationModel();
    }

    @Override
    public ResourceAdministrationView createView() {
        return this;
    }

    @Override
    public ResourceAdministrationPresenterImpl createPresenter() {
        return new ResourceAdministrationPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {
    }

    @Override
    public void onResume() {
        super.onResume();
        isDataInitiated = false;
        presenter.requestAccount(Params.getAccountPamars(accountName));
    }

}
